<?php
$CONFIG['current_mysql_credentials']['mysql_database'] = 'techcenter';
$CONFIG['current_mysql_credentials']['mysql_user'] = 'techcenter';
$CONFIG['current_mysql_credentials']['mysql_pass'] = 'Btv6Et6ARThrjbQb';
$USER = array();
$PARATURE = array();

function getCurrentTime($military = false){
	if(!$military){
		return date('g:i A');
	}else{
		return date('G:i');
	}
}

function getCurrentDate($formal = false){
	if(!$formal){
		return date('n/j/Y');
	}else{
		return date('F j, Y');
	}
}

function getPageURL(){
	return basename($_SERVER['REQUEST_URI']);
}

function getPageFileName(){
	$file = substr($_SERVER['SCRIPT_NAME'], 1);
	$file = explode("?", basename($file));
	$file = explode(".", $file[0]);
	return $file[0];
}

function getMenu($type){
	$sql = "SELECT * FROM `tbMenus` WHERE `sPortalVersion` = '*' AND `sMenuType` = :type";
	$q = db::Query($sql, array(':type'=>$type));
	$row = $q->fetch();
	$sql = "SELECT * FROM `tbMenus` WHERE `sPortalVersion` = :prefix AND `sMenuType` = :type";
	$q = db::Query($sql, array(':prefix'=>getPortalPrefix(), ':type'=>$type));
	$row2 = $q->fetch();
	if($type == "navbar"){
		return $row['sMenuData'].$row2['sMenuData'].'<li><a href="https://www.edison.edu/webservices/internal/request/bug_report_page.php" title="Click here to submit a Bug Report" target="_new">Submit a Bug Report</a></li>';
	}else{
		return $row['sMenuData'].$row2['sMenuData'];
	}
}

function sendEmail($to, $subject, $body){
	global $CONFIG;
	if($CONFIG['allowEmails'] == 'true'){
		$bod = '<center><table width="100%"><tr><td align="center">';
		$bod .= "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		$bod .= "\n";
		$bod .= "Edison State College\n";
		$bod .= "Technology Support Center Portal System\n";
		$bod .= "\n";
		$bod .= "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		$bod .= "\n</td></tr><tr><td>";
		$bod .= $body."</td></tr><tr><td align='center'>";
		$bod .= "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
		$bod .= "If you are having problems with the portal system please submit a web request at: <a 	href='http://www.edison.edu/webservices/internal/request/'>http://www.edison.edu/webservices/internal/request/</a>";
		$bod .= "\n";
		$bod .= "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
		$bod .= "</td></tr></table>";
		$bod = str_replace("\n", "<br>", $bod);
		$bod = rtrim(chunk_split(base64_encode($bod)));
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= 'Content-Transfer-Encoding: base64'."\r\n";
		$headers .= 'From: '.$CONFIG['emailFrom'];
		mail($to, $subject, $bod, $headers);
	}
}

function checkActiveLogin(){
	if($_SESSION['username'] == NULL){
		gotoPage('login.php');
	}
}

function customerSignIn($name, $reason){
	global $USER;
	$cust_name = urlencode($name);
	$cust_reason = urlencode($reason);
	$cust_UID = '';
	
	$ch = curl_init('http://www.edison.edu/techtraining/submittechcentervisit.php');
    curl_setopt ($ch, CURLOPT_REFERER, 'http://www.edison.edu/techtraining/techcenter.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // We don't want to output the response
    $postvars = "name=".$cust_name."&uid=".$cust_UID."&visitreason=".$cust_reason."&action=submit&button=%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0Complete+Sign+In%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0";
    
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $postvars);
    curl_setopt ($ch, CURLOPT_POST, 1);
    
    if(!curl_exec($ch)) {
		$subject = "Portal Error";
		$body = "The following error occured while trying to sign a customer in.  The submission info follows.<br/>=======================================================<br/>Customer Name: ".$cust_name."<br/><br/>Customer Reason: ".$cust_reason."<br/><br/>Error Returned: ".curl_error($ch)."<br/><br/>Referring User: ".$usr_info['sFname']." ".$usr_info['sLname']."<br/>=======================================================<br/><br/>This error has been sent to all administrators.";
		sendEmail('kpeterson5@edison.edu', $subject, $body);
		$_GET['err'] = "An error occurred while signing in that customer.<br/><br/>The information has been email to the developers and they will be sure to submit it as soon as they fix the problem.";
    }else{
		$SQL = "INSERT INTO `tbSignins` (sTech, sCustName, sBannerId, sProbDesc, sDateTime) VALUES (:tech, :cust, '',:reason, :date)";
		db::Query($SQL, array(':tech'=>$USER['sFname']." ".$USER['sLname'], ':cust'=>$name, ':reason'=>$reason, ':date'=>getCurrentDate(true)." @ ".getCurrentTime()));
	}
    curl_close($ch);
}

function getPortalName(){
	global $USER;
	if($USER['sLevel'] == 'Super Administrator' or $USER['sLevel'] == 'Administrator'){
		return 'Administration Portal System';
	}elseif($USER['sLevel'] == 'Technology Support Center'){
		return 'Technology Support Center Portal System';
	}elseif($USER['sLevel'] == 'Business Lab'){
		return 'K-103 Business Lab Portal System';
	}else{
		return 'Desktop Support Portal System';
	}
}

function getPortalPrefix(){
	global $USER;
	if($USER['sLevel'] == 'Super Administrator' or $USER['sLevel'] == 'Administrator'){
		return 'aps_';
	}elseif($USER['sLevel'] == 'Technology Support Center'){
		return 'tps_';
	}elseif($USER['sLevel'] == 'Business Lab'){
		return 'kps_';
	}else{
		return 'dps_';
	}
}

function getConfig(){
	global $CONFIG;
	$sql = "SELECT * FROM `tbConfig`";
	$q = db::Query($sql);
	while($row = $q->fetch()){
		$CONFIG[$row['sConfigName']] =$row['sConfigValue'];
	}
	ini_set("session.gc_maxlifetime", $CONFIG['sessionTimeoutTime']);
}

function getWeather($part = 'cont'){
	$desc = "";
	$doc = new DOMDocument();
	$doc->load('http://weather.yahooapis.com/forecastrss?w=2405872');
	$channel = $doc->getElementsByTagName("channel");
	foreach($channel as $chnl){
		$item = $chnl->getElementsByTagName("item");
		foreach($item as $itemgotten){
			$describe = $itemgotten->getElementsByTagName("description");
			$description = $describe->item(0)->nodeValue;
			$desc .= $description;
		}
	}
	$temp = explode("<br />", $desc);
	if($part == 'img'){
		$desc = str_replace('<img src="', '', $temp[0]);
		$desc = str_replace('"/>', '', $desc);
	}else{
		$temp = explode("<BR />", $temp[2]);
		$desc = $temp[0];
	}
	return $desc;
}

function getRealName(){
	global $USER;
	return $USER['sFname']." ".$USER['sLname'];
}

function addActivity($activity){
	global $USER, $CONFIG;
	$sql = "INSERT INTO `tbActivity` VALUES (null, :name, :date, :time, :activity)";
	db::Query($sql, array(':name'=>$USER['sFname']." ".$USER['sLname'], ':date'=>getCurrentDate(), ':time'=>getCurrentTime(), ':activity'=>$activity));
}

function getUserInfo($username = NULL){
	global $USER, $PARATURE;
	if($username == NULL){
		$username = $_SESSION['username'];
	}
	$sql = "SELECT * FROM `tbUsers` WHERE `sUname` = :uname";
	$q = db::Query($sql, array(':uname'=>$username));
	$row = $q->fetch();
	if($row['iID'] != ''){
		foreach($row as $key=>$value){
			$USER[$key] = $value;
		}
		$sql = "SELECT * FROM `tbParatureCache` WHERE `sUname` = :uname";
		$q = db::Query($sql, array(':uname'=>$username));
		$row = $q->fetch();
		if($row['iID'] != ''){
			foreach($row as $key=>$value){
				$PARATURE[$key] = $value;
			}
		}
		
		$sql = "SELECT * FROM SPRIDEN, GOBTPAC WHERE SPRIDEN_PIDM = GOBTPAC_PIDM AND GOBTPAC_EXTERNAL_USER = :uname AND SPRIDEN_CHANGE_IND is null";
		$q = Oracle::Query($sql, array(':uname'=>$username));
		$row = $q->fetch();
		$USER['sFname'] = $row['SPRIDEN_FIRST_NAME'];
		$USER['sMname'] = $row['SPRIDEN_MI'];
		$USER['sLname'] = $row['SPRIDEN_LAST_NAME'];
		if($USER['iPidm'] == 0){
			$sql = "UPDATE `tbUsers` SET `iPidm` = :pidm WHERE `iID` = :id";
			db::Query($sql, array(':pidm'=>$row['SPRIDEN_PIDM'], ':id'=>$USER['iID']));
			$USER['iPidm'] = $row['SPRIDEN_PIDM'];
		}
		if($USER['iSamba'] == 0){
			fopen("http://techcenter.edisone.edu/createUser.php?uname=".$USER['sUname']."&name=".urlencode($USER['sFname']." ".$USER['sLname'])."&pword=".urlencode($_SESSION["MM_Password"]), 'r');
			$sql = "UPDATE `tbUsers` SET `iSamba` = 1 WHERE `iID` = :id";
			db::Query($sql, array(':id'=>$USER['iID']));
		}else{
			fopen("http://techcenter.edisone.edu/createUser.php?uname=".$USER['sUname']."&pword=".urlencode($_SESSION["MM_Password"])."&update=".getPageFileName(), 'r');
		}
		$sql = "SELECT * FROM `tbEmployees` WHERE `sFname` = :fname AND `sLname` = :lname";
		$q = db::Query($sql, array(':fname'=>$USER['sFname'], ':lname'=>$USER['sLname']));
		$row = $q->fetch();
		if($row['iID'] != NULL){
			$sql = "SELECT * FROM `tbTimecard` WHERE `iEmployeeID` = :id ORDER BY `iID` DESC";
			$q = db::Query($sql, array(':id'=>$row['iID']));
			$r = $q->fetch();
			if($r['sAction'] != "Punch In" and getPageFileName() != "SignInFirst" and getPageFileName() != "logout"){
				gotoPage("SignInFirst.php");
				exit;
			}
		}
		if($USER['sDisabled'] == 'Y'){
			echo "Your account is disabled.  Please contact Kody for assistance.";
			unset($_SESSION['username']);
			exit;			
		}
		initCometChat();		
	}else{
		unset($_SESSION['username']);
	}
}

function initCometChat(){
	global $USER, $CONFIG;
	$CONFIG['current_mysql_credentials']['mysql_database'] = 'cometchat';
	$CONFIG['current_mysql_credentials']['mysql_user'] = 'cometchat';
	$CONFIG['current_mysql_credentials']['mysql_pass'] = 'nC8pJ4HHE24f7sGb';
	db::disconnect();
	
	$sql = "SELECT * FROM `users` WHERE `username` = :username";
	$q = db::Query($sql, array(':username'=>$_SESSION['username']));
	$row = $q->fetch();
	if($row['userid'] == ''){
		$sql = "INSERT INTO `users` VALUES(:username, null, :time, '', :name, '')";
		db::Query($sql, array(':username'=>$_SESSION['username'], ':time'=>time(), ':name'=>$USER['sFname']." ".$USER['sLname']));
		sendEmail('kpeterson5@edison.edu', 'New CometChat User', "New CometChat User Created!<br/><br/>User: ".$USER['sFname']." ".$USER['sLname']);
	}
	
	$CONFIG['current_mysql_credentials']['mysql_database'] = 'techcenter';
	$CONFIG['current_mysql_credentials']['mysql_user'] = 'techcenter';
	$CONFIG['current_mysql_credentials']['mysql_pass'] = 'Btv6Et6ARThrjbQb';
	db::disconnect();
}

function gotoPage($page, $wait = 0){
	echo "<meta http-equiv='refresh' content='".$wait.";URL=".$page."' />";
	exit;
}

function checkLastSBuilding(){
	$sql = "SELECT * FROM `tbSBuildingReports` ORDER BY `iID` DESC LIMIT 0,1";
	$q = db::Query($sql);
	$row = $q->fetch();
	$last = strtotime($row['sDate']." ".$row['sTime']);
	$now = time();
	$last = $now - $last;
	if($last > 21600){
		return true;
	}else{
		return false;
	}
}

function checkLastInventory(){
	global $CONFIG;
	$CONFIG['current_mysql_credentials']['mysql_database'] = 'inventory';
	$CONFIG['current_mysql_credentials']['mysql_user'] = 'inventory';
	$CONFIG['current_mysql_credentials']['mysql_pass'] = '8DNWxqKDNhTwdBfY';
	db::disconnect();
	
	$sql = "SELECT * FROM `tbAnnualRooms` WHERE `sCampus` = :campus ORDER BY `iTimeStamp` DESC";
	$q = db::Query($sql, array(':campus'=>'R1'));
	$row = $q->fetch();
	
	$last = time() - $row['iTimeStamp'];
	
	$CONFIG['current_mysql_credentials']['mysql_database'] = 'techcenter';
	$CONFIG['current_mysql_credentials']['mysql_user'] = 'techcenter';
	$CONFIG['current_mysql_credentials']['mysql_pass'] = 'Btv6Et6ARThrjbQb';
	db::disconnect();
	
	if($last > 21600){
		return true;
	}else{
		return false;
	}
	
}

function getPrinterInfo($ip, $request){
	$temp = file_get_contents('http://'.$ip.'/cgi-bin/dynamic/printer/PrinterStatus.html');
	$temp = explode('<td>', $temp);
	if($request == 'toner'){
		$toner = explode('</td>', $temp[1]);
		return $toner[0];
	}
	if($request == 'paper'){
		$paper = explode('</TD>', $temp[3]);
		if($paper[0] == '<b>OK</b>'){
			return '<b>Paper Level - OK</b>';
		}else{
			return '<b style="color:red">Paper Level - LOW</b>';
		}
	}
}

function getParatureCount($token){
	$openTickets = 0;
	
	$temp = simplexml_load_file('https://d2.parature.com/api/v1/3781/4076/Ticket?_my_tickets_=true&_pageSize_=100&_order_=Date_Created_desc_&_token_='.$token);
	foreach($temp as $key=>$value){
		foreach($value as $key2=>$value2){
			if($key2 == "Ticket_Status"){
				foreach($value2 as $key3=>$value3){
					foreach($value3 as $key4=>$value4){
						if($value4 == "Edison: Solved" or $value4 == "Edison: Closed"){
						}else{
							$openTickets ++;
						}
					}
				}
			}
		}
	}
	return $openTickets;
}
?>